# -*- coding: utf-8 -*-
import ast
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.agentpay.base import AbstractHandler
from common.agentpay.db import get_agent_pay_order
from common.channel import admin_db as channel_admin_db
from common.channel.pay import check_channel_order
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address
from common.utils.types import Enum
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '1964': {  # 智信付支付 99-20000 2.5% 支付宝 dwc
        'API_KEY': '5u31xD9994jp795Kyu24z6q05Ugl8I97rC',
        'gateway': 'http://service.ba4e67f.tb366.com/PayOrder/V3',
        'query_gateway': 'http://service.ba4e67f.tb366.com/PayOrder/QueryPayOrderV3',
        'draw_gateway': 'http://service.ba4e67f.tb366.com',
        'draw_query_gateway': 'http://service.ba4e67f.tb366.com',
        'balance_query_gateway': 'http://service.ba4e67f.tb366.com',
    },
}

NOTIFY_PAY_STATUS = Enum({
    "WAIT": (0, u"等待"),
    "SUCCESS": (1, u"成功"),
    "FAIL": (2, u"失败"),
})


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_draw_gateway(mch_id):
    return APP_CONF[mch_id]['draw_gateway']


def _get_draw_query_gateway(mch_id):
    return APP_CONF[mch_id]['draw_query_gateway']


def _get_balance_gateway(mch_id):
    return APP_CONF[mch_id]['balance_query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(parameter, key):
    s = ''
    sorted_keys = sorted(parameter, key=str.lower)
    for k in sorted_keys:
        if parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    s = s[:-1] + '%s' % key
    _LOGGER.info("zhixinfupay agentpay sign string: %s", s)
    return _gen_sign(s)


def generate_verify_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    s = s[:-1] + '%s' % key
    _LOGGER.info("zhixinfupay verify sign string: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['Sign']
    params.pop('Sign')
    calculated_sign = generate_verify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("zhixinfupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay_red_packet':
        return '10'
    elif service == 'alipay2card':
        return '11'
    elif service == 'alipay_auto':
        return '19'
    elif service == 'unionpay':
        return '22'
    return '11'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    service = info.get('service')
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('Amount', pay_amount),
        ('ChannelPlatform', _get_pay_type(service)),
        ('Ip', _get_device_ip(info)),
        ('MerchantId', app_id),
        ('MerchantUniqueOrderId', str(pay.id)),
        ('NotifyUrl', '{}/pay/api/{}/zhixinfupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('ReturnUrl', '{}/pay/api/{}/zhixinfupay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('Timestamp', local_now().strftime("%Y%m%d%H%M%S")),
    ))
    parameter_dict['Sign'] = generate_sign(parameter_dict, api_key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("zhixinfupay create rsp data: %s", response.text)
    return {'charge_info': json.loads(response.text)['Url']}


def check_notify_sign(request, app_id):
    _LOGGER.info("zhixinfupay notify body: %s", request.body)
    data = dict(request.POST.iteritems())
    _LOGGER.info("zhixinfupay notify data: %s, order_id is: %s", data, data['MerchantUniqueOrderId'])
    verify_notify_sign(data, _get_api_key(app_id))
    pay_id = data['MerchantUniqueOrderId']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('zhixinfupay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = ''
    trade_no = ''
    total_fee = float(data['Amount'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    _LOGGER.info('zhixinfupay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
    add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
    # async notify
    async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('MerchantId', app_id),
        ('MerchantUniqueOrderId', str(pay_order.id)),
        ('Timestamp', local_now().strftime("%Y%m%d%H%M%S")),
    ))
    parameter_dict['Sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('zhixinfupay query data %s, order_id is: %s', json.dumps(parameter_dict),
                 parameter_dict['MerchantUniqueOrderId'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info('zhixinfupay query rsp, %s', response.text)
    data = json.loads(response.text)
    if response.status_code == 200:
        trade_status = str(data['PayOrderStatus'])
        total_fee = float(pay_order.total_fee)
        trade_no = ''
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        # 0为尚未支付，100为支付成功，-90为支付失败
        if trade_status == '100':
            check_channel_order(pay_id, total_fee, app_id)
            _LOGGER.info('zhixinfupay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            if res:
                async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('zhixinfupay data error, status_code: %s', response.status_code)


def _get_bank_type(bank_type):
    if bank_type == 'ICBC':
        return '1002'
    elif bank_type == 'CCB':
        return '1003'
    elif bank_type == 'PNB':
        return '1010'
    elif bank_type == 'BOC':
        return '1052'
    elif bank_type == 'ABC':
        return '1005'
    elif bank_type == 'BCM':
        return '1020'
    elif bank_type == 'CMB':
        return '1001'
    elif bank_type == 'CNCB':
        return '1021'
    elif bank_type == 'CEB':
        return '1022'
    elif bank_type == 'HXB':
        return '1025'
    elif bank_type == 'SPDB':
        return '1004'
    elif bank_type == 'CIB':
        return '1009'
    elif bank_type == 'CMBC':
        return '1006'
    elif bank_type == 'CGB':
        return '1027'
    elif bank_type == 'PSBC':
        return '1028'
    else:
        return 'THIRD_NOT_SUPPORT'


def _get_bank_name(bank_type):
    if bank_type == 'ICBC':
        return '工商银行'
    elif bank_type == 'CCB':
        return '建设银行'
    elif bank_type == 'PNB':
        return '平安银行'
    elif bank_type == 'BOC':
        return '中国银行'
    elif bank_type == 'ABC':
        return '农业银行'
    elif bank_type == 'BCM':
        return '交通银行'
    elif bank_type == 'CMB':
        return '招商银行'
    elif bank_type == 'CNCB':
        return '中信银行'
    elif bank_type == 'CEB':
        return '光大银行'
    elif bank_type == 'HXB':
        return '华夏银行'
    elif bank_type == 'SPDB':
        return '浦发银行'
    elif bank_type == 'CIB':
        return '兴业银行'
    elif bank_type == 'CMBC':
        return '民生银行'
    elif bank_type == 'CGB':
        return '广发银行'
    elif bank_type == 'PSBC':
        return '邮政银行'
    else:
        return 'THIRD_NOT_SUPPORT'


class ZhiXinFuPayHandler(AbstractHandler):
    def submit_order(self, order_no):
        """
        创建代付请求
        :return:
        """
        agent_pay = get_agent_pay_order(order_no)
        chn = channel_admin_db.get_channel(int(agent_pay.channel_id))

        chn_info = json.loads(chn.info)
        app_id = chn_info['app_id']
        api_key = _get_api_key(app_id)
        params = {
            'MerchantId': app_id,
            'MerOrderNo': agent_pay.order_no,
            'OrderMoney': int(agent_pay.total_fee * 100),
            'BankCode': _get_bank_type(agent_pay.bank_code),
            'Timestamp': int(time.time()),
            'Province': agent_pay.account_province.encode('utf-8'),
            'City': agent_pay.account_city.encode('utf-8'),
            'CardNo': agent_pay.card_no,
            'CardName': agent_pay.account_name.encode('utf-8'),
        }
        params['sign'] = generate_sign(params, api_key)
        _LOGGER.info('zhixinfupay draw data: %s', json.dumps(params))
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        response = requests.post(_get_draw_gateway(app_id), data=params, timeout=3, headers=headers, verify=False)
        _LOGGER.info("zhixinfupay draw rsp data: %s %s", response.status_code, response.text)
        data = json.loads(response.text)
        if data['Code'] == '1':
            return params['MerOrderNo'], '', '提交成功->' + str(response.text)
        else:
            return params['MerOrderNo'], '', '提交失败->' + str(response.text)

    def query_agent_pay(self, order_no):
        """
        查询代付请求
        :return:
        """
        agent_pay = get_agent_pay_order(order_no)
        chn = channel_admin_db.get_channel(int(agent_pay.channel_id))
        chn_info = json.loads(chn.info)
        app_id = chn_info['app_id']
        api_key = _get_api_key(app_id)
        params = {
            'MerchantId': app_id,
            'MerOrderNo': agent_pay.order_no,
        }
        params['Sign'] = generate_sign(params, api_key)
        _LOGGER.info('zhixinfupay draw query data: %s', json.dumps(params))
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        response = requests.post(_get_draw_query_gateway(app_id), data=params, timeout=3, headers=headers, verify=False)
        _LOGGER.info("zhixinfupay draw query rsp data: %s %s", response.status_code, response.text)
        if response.status_code != 200:
            raise ParamError('zhixinfupay query_agent_pay error')
        return str(response.text)

    def query_balance(self, info):
        info = ast.literal_eval(info.encode("utf-8"))
        app_id = info['app_id']
        api_key = _get_api_key(app_id)
        params = {
            'MerchantId': app_id,
        }
        params['Sign'] = generate_sign(params, api_key)
        _LOGGER.info('zhixinfupay balance query data: %s', json.dumps(params))
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        response = requests.post(_get_balance_gateway(app_id), data=params, timeout=3, headers=headers, verify=False)
        _LOGGER.info("zhixinfupay balance query rsp data: %s %s", response.status_code, response.text)
        if response.status_code != 200:
            raise ParamError('zhixinfupay query_agent_pay error')
        data = json.loads(response.text)
        return float(data['Money']) / 100.0


handler = ZhiXinFuPayHandler()
